/*
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sm.healthy.base

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.sm.healthy.data.bean.*
import com.sm.healthy.data.dao.*

@Database(
    entities = [UserEntity::class, BloodPressureEntity::class,
        OxygenEntity::class, EcgEntity::class,
        Spo2Entity::class, FetalEntity::class, TemperatureEntity::class],
    version = 10,
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {

    abstract fun userDao(): UserDao
    abstract fun bloodPressureDao(): BloodPressureDao
    abstract fun fetalDao(): FetalDao
    abstract fun oxygenDao(): OxygenDao
    abstract fun temperatureDao(): TemperatureDao
    abstract fun ecgDao(): EcgDao
    abstract fun spo2Dao(): Spo2Dao

    companion object {

        private const val DATABASE_NAME = "healthy-db"

        @Volatile
        private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
                .fallbackToDestructiveMigration()//数据库更新时删除数据重新创建
                .build()
        }
    }
}
